package com.vast.vastlcd.dialog;

import java.text.ParseException;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import com.vast.vastlcd.connection.IConnection;
import com.vast.vastlcd.connection.LCDPipeConnection;
import com.vast.vastlcd.connection.LCDSocketConnection;

public class SWTConnectionDialog extends TitleAreaDialog {

	private IConnection connection = null;
	private String pipeName;
	private String hostname;
	private int portvalue;
	private boolean createConnection;
	private boolean usePipe;
	
	@Override
	protected void okPressed() {
		super.okPressed();
		
		if (usePipe) {
			connection = new LCDPipeConnection(pipeName,createConnection);
		} else {
			connection = new LCDSocketConnection(hostname,portvalue,createConnection);
		}
	}

	private SWTConnection content = null;
	
	@Override
	protected Control createDialogArea(Composite parent) {
		this.getShell().setText("Configuration");
		this.getButton(IDialogConstants.OK_ID).setEnabled(false);
		this.setTitle("VCD Connection Configuration");
		this.setMessage("Test of a new message !");
		content = new SWTConnection(this, parent, SWT.NONE);
		return content;
	}

	public SWTConnectionDialog(Shell parentShell) {
		super(parentShell);
		this.setBlockOnOpen(true);
	}
	

	public IConnection getConnection() {
		return connection;
	}
	
	public void validateContent() {
		try {
			this.createConnection = content.checkBox.isEnabled();
			if (content.pipeRadio.isEnabled()) {
				if (content.pipeName.getText().matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
					this.pipeName = content.pipeName.getText();
					this.usePipe = true;			
					this.getButton(IDialogConstants.OK_ID).setEnabled(true);
				} else {
					this.setMessage("Incorrect Pipe Name!");
					this.getButton(IDialogConstants.OK_ID).setEnabled(false);
				}
			} else {
				String message = "";
				if (content.HostName.getText().matches("[a-zA-Z_][a-zA-Z0-9_]*"))
					this.hostname = content.HostName.getText(); 
				else
					message += "Incorrect hostname !\n";
				try {
					this.portvalue = Integer.parseInt(content.Port.getText());
					if (portvalue>9999) 
						message += "Incorrect Port Value !\n";
				} catch (NumberFormatException e) {
					e.printStackTrace();
					message += "Incorrect Port Value !\n";
				}
				
				if (message.equals("")) {
					this.getButton(IDialogConstants.OK_ID).setEnabled(true);
				} else {
					this.setMessage(message);
					this.getButton(IDialogConstants.OK_ID).setEnabled(false);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.getButton(IDialogConstants.OK_ID).setEnabled(false);
		}
	}

}
